<?php

namespace control;

/*
*个税核算类
*/

class personalTaxClass extends adIndexClass
{
    private const title = '个税核算';
    private const page = 'personalTax';
    private const pageDeduction = 'personalTaxDeduction';
    private const table = 'personal_tax';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'deductionSearch':
                $tr = [
                    'department'      => [
                        'name'  =>  L('salary.table.bu_men'),
                        'width' => 300,
                    ],
                    'job' => [
                        'name'  => L('salary.table.zhi_wei'),
                        'width' => 300,
                    ],
                    'name'  => [
                        'name'  => L('salary.table.yuan_gong'),
                        'width' => 300,
                    ],
                    'decText'         => [
                        'name'  => L('salary.table.gskk') . '(' . static::$unit . ')',
                        'width' => 300,
                    ],
                    'text'          => [
                        'name'  => L('salary.table.bei_zhu'),
                        'width' => 300,
                    ]
                ];
                break;
            default:
                $tr = [
                    'department'      => [
                        'name'  => L('salary.table.bu_men'),
                        'width' => 300,
                    ],
                    'job' => [
                        'name'  => L('salary.table.zhi_wei'),
                        'width' => 300,
                    ],
                    'name'  => [
                        'name'  => L('salary.table.yuan_gong'),
                        'width' => 300,
                    ],
                    'month'         => [
                        'name'  => L('salary.table.jiao_na_yue_fen'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'tax'          => [
                        'name'  => "个税(" . static::$unit . ")",
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function deductionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.bu_men')     => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 设备扣款
     *
     */
    public function deduction()
    {
        $html = $this->deductionOptions(false);
        //控件
        $button = "";
        if ($this->power(self::pageDeduction, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'commitDec', {})\">" . L('clock.table.decMoney') . "</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function deductionSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = " and isCommit = 0";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $arr = explode('~', $this->post('moon'));
            $arr[0] = trim($arr[0]);
            $arr[1]   = trim(end($arr));
            $and .=" and month >= '$arr[0]' and month <='$arr[1]'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month desc,id',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 500, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("recordForm", "recordId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "recordId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "name":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case "decText":
                        $decText = text(array('name' => "decMoney[$array[id]]", 'class' => 'text textPrice', 'value' => $array['tax']));
                        $row[] = $decText;
                        break;
                    case "text":
                        $text = text(array('name' => "text[$array[id]]", 'class' => 'text textPrice', 'value' => ''));
                        $row[] = $text;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='recordForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 提交扣款
     * @return bool|string
     */
    public function commitDec()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') => L('salary.table.tax_warn'),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('salary.table.gskk'), "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'recordForm'));
    }

    /**
     * 账户扣款编辑
     * @return bool|string
     */
    public function commitDecEdit()
    {
        $listId = $this->post('recordId');
        $textArr = $this->post('text');
        $decMoneyArr = $this->post('decMoney');
        if (!$this->power(self::pageDeduction, "edit")) {
            $json['warn'] = L('salary.table.tax_edit_permission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        } else {
            $x = 0;
            foreach ($listId as $k => $id) {
                $info = query(self::table, " id = '$id'");
                $staff = query('staff', " stid = '$info[staffId]'");
                $warn = update(array(
                    "table" => self::table,
                    "field" => [
                        'decMoney' => $decMoneyArr[$id],
                        'text' => $textArr[$id],
                        'stid' => $this->control['stid'],
                        'isCommit' => 1,
                    ],
                    'where' => " id = '$id'"
                ));
                if ($warn == '更新成功') {
                    $x++;
                    //添加日志
                    $text = str_replace(['{{staffName}}', '{{name}}', '{{month}}'], [$this->control['name'], $staff['name'], $info['month']], L('salary.table.tax_commit_log'));
                    $this->logText(["type" => self::pageDeduction, "text" => $text]);
                }
            }
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.tax_commit_text'));
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.bu_men')     => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    L('salary.table.jiao_na_yue_fen')     => text(array("name" => "moon",'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 查询条件
     *
     * @param string $workFlow
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('salary.table.shan_chu') . "</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*社保数据-列表页-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            "stid" => $this->post('stid'),//员工
        );
        $and = '';
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and stid in (select stid from staff where jobId in (select id from job where departmentId = '{$this->post('departmentId')}')) ";
        }
        if ($this->post('moon')) {
            $arr = explode('~', $this->post('moon'));
            $arr[0] = trim($arr[0]);
            $arr[1]   = trim(end($arr));
            $and .=" and month >= '$arr[0]' and month <='$arr[1]'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "name":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(tax),0) as tax",
        ]);
        $total    = [
            'tax'      => $totalQuery['tax'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '您还没有导入的权限';
        }else {
            $exampleData[] = ['张三', '500223199510111111', '202101', 100, '样例数据，导入时请删除本条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '姓名'=>$example[0],
                            '身份证号'=>$example[1],
                            '缴纳月份'=>$example[2],
                            '个税'=>$example[3],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.tax_template'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /*数据导入分析-个税*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = "您还没有导入的权限";
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $IDCard = $cell['身份证号'];//身份证号码
                    $talent = query('talent_pool', " idCard = '$IDCard'");
                    $staff = query("staff", "talentId = '$talent[id]'");
                    $moon = date('Y-m', strtotime($cell['缴纳月份'] . '01'));
                    $field = array(
                        "id" => self::getId(),
                        "staffId" => $staff['stid'],//员工ID
                        'jobId' => $staff['jobId'],
                        "month" => $moon,//缴款月份
                        "tax" => $cell['个税'],//个税
                        'isCommit'=>1,
                    );
                    $line = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                    if (empty($field['staffId']) || !$talent['id']) {
                        $text .= $line . "：" . L('salary.table.find_no_staff') . "\n";
                    } elseif (sqlNum(self::table, "staffId = '$staff[stid]'  and month = '$moon' ") > 0) {
                        $text .= $line . ":" . str_replace(['{{idCard}}'], [$IDCard], L('salary.table.exist_data'));
                    } else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= $line . "：" . L('job.other.import_success') . "<br>";
                        } else {
                            $text .= $line . "：" . L('job.other.import_failed') . "<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.taxDel');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];

            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                $work_sign_record = query('work_sign_record', "month = '$info[month]' and stid = '$info[staffId]' and isChecked = 1");
                if (!empty($work_sign_record['id'])) {
                    $text = self::findStaff($info['staffId']) . "的工资已核算，不能删除个税记录<br>";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = L('salary.table.sccg');
                    $x++;
                    $text .= str_replace(['{{name}}', '{{month}}'], [self::findStaff($info['staffId']), $info['month']], L('salary.table.tax_del_text')) . $warn . "。<br>";
                }

            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('salary.table.tax_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('salary.table.tax_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                    'isMust'=>true,
                    'isRepeat'=>true,
                ],
                [
                    'columnName'=>'缴纳月份',
                    'aliasName'=>'缴纳月份',
                    'isMust'=>true,
                    'isRepeat'=>true,
                ],
                [
                    'columnName'=>'个税',
                    'aliasName'=>'个税',
                    'isMust'=>true,
                ],
            ]
        };
    }

}
